﻿using aier.dataaccess.model;
using aier.dataaccess.dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using aier.xrm.wcf;
using Microsoft.Xrm.Sdk;
using log4net;

namespace aier.business.logic
{
    public class AppointmentBll
    {
        public AppointmentDal appointmentDal { get; set; }

        public CommonWcf commonWcf { get; set; }

        public ILog log { get; set; }

        public ResResult resResult { get; set; }

        /// <summary>
        /// 根据时间查询预约
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <returns></returns>
        public IEnumerable<AppointmentView> QueryAppointmentByTime(string starttime,string endtime)
        {
              return appointmentDal.QueryAppointmentByTime(starttime, endtime);       
        }


        /// <summary>
        /// 插入拜访
        /// </summary>
        /// <param name="appointmenMolde"></param>
        public ResResult AddAppointment(AppointmenMolde appointmenMolde)
        {
            Guid resultId = Guid.Empty;
            try {
                if (appointmenMolde != null)
                {
                    Entity entity = appointmenMolde.AsCrmEntity();
                    if (Guid.Empty.Equals(appointmenMolde.userid))
                    {
                        resultId = commonWcf.CreateEntity(entity);
                    }
                    else
                    {
                        resultId = commonWcf.CreateEntityProxy(appointmenMolde.userid, entity);
                    }

                  
                    return resResult.SuccessResult(resultId);
                }
                else {
                    
                    return resResult.FailResult("AppointmentBll->AddAppointment:传入实体为空或id为空");
                }
               
            } catch (Exception e) {
                log.Error("AddAppointment方法错误：" + e.Message);
                return resResult.FailResult("AppointmentBll->AddAppointment Error:"+e.Message);
            }
            
        }

        /// <summary>
        /// 删除拜访
        /// </summary>
        /// <param name="activityid"></param>
        public ResResult DelAppointment(Guid activityid)
        {
            try
            {
                if (!Guid.Empty.Equals(activityid))
                {
                    commonWcf.DeleteEntityById("appointment", activityid);
                    return resResult.SuccessResult(activityid);
                }
                return resResult.FailResult("AppointmentBll->DelAppointment Error: 传入id为空");
            }
            catch (Exception e)
            {
                log.Error("DelAppointment方法出错：" + e.Message);
                return resResult.FailResult("AppointmentBll->DelAppointment Error:" + e.Message);
            }
            
        }

        /// <summary>
        /// 更新拜访信息
        /// </summary>
        /// <param name="appointmenMolde"></param>
        public ResResult ModAppointment(AppointmenMolde appointmenMolde) {

            try
            {
                if (appointmenMolde == null)
                {
                    return resResult.FailResult("AppointmentBll->ModAppointment Error: 传入对象为空");
                }
                if (Guid.Empty.Equals(appointmenMolde.activityid))
                {
                    return resResult.FailResult("AppointmentBll->ModAppointment Error: 传入id为空");
                }
                if (QryAppointment(appointmenMolde.activityid) == null) {
                    return resResult.FailResult("AppointmentBll->ModAppointment Error: 不存在该拜访信息");
                }
                Entity entity = appointmenMolde.AsCrmEntity();
                if (Guid.Empty.Equals(appointmenMolde.userid))
                {
                    commonWcf.UpdateEntityById(entity);
                }
                else {
                    commonWcf.UpdateEntityProxyById(appointmenMolde.userid, entity);
                }

                return resResult.SuccessResult(appointmenMolde.activityid);
            }
            catch (Exception e) {
                log.Error("ModAppointment方法出错：" + e.Message);
                return resResult.FailResult("AppointmentBll->ModAppointment Error:" + e.Message);
            }
           

        }

        /// <summary>
        /// 更新状态（modAppointmentStatus（String activityid,int statuscode,DoctorUser doctorUser））
        /// </summary>
        /// <param name="activityid"></param>
        /// <param name="stutsCode"></param>
        public ResResult UpdateStatus(Guid activityid,int stateCode,int stutsCode) {
         
            try {
                if ( Guid.Empty.Equals(activityid))
                {
                    return resResult.FailResult("AppointmentBll->UpdateStatus Error: 传入id为空");
                }
                commonWcf.UpdateStateRequestWithStatus(activityid, stateCode, stutsCode, "appointment");
                return resResult.SuccessResult(activityid);
            } catch (Exception e) {
                log.Error("UpdateStatus 方法出错：" + e.Message);
                return resResult.FailResult("AppointmentBll->UpdateStatus Error:" + e.Message);
            }
        }

        /// <summary>
        /// 根据负责人查询区域下拉列表
        /// </summary>
        /// <param name="ownerid">负责人id
        /// </param>
        /// <returns></returns>
        public IEnumerable<AppointmentView> QryDistrictandcountyList(Guid ownerid)
        {          
                return  appointmentDal.QryDistrictandcountyList(ownerid);           
        }

        /// <summary>
        /// 分页查询查询拜访列表qryAppointmentList(int fromIndex, int toIndex, String sort, String ownerid)
        /// </summary>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页信息条数</param>
        /// <param name="sort">排序方式（asc或desc）</param>
        /// <param name="ownerid">负责人id</param>
        /// <returns></returns>
        public IEnumerable<AppointmentView> QryAppointmentListPage(int pageNum, int pageSize, string sort
            , Guid ownerid,string starttime, string endtime) {
                return  appointmentDal.QryAppointmentListPage(pageNum, pageSize, sort, ownerid, starttime, endtime);
        }

        /// <summary>
        /// 根据区域id，状态，负责人查询拜访视图
        /// </summary>
        /// <param name="new_districtandcounty">区域id</param>
        /// <param name="statecode">状态</param>
        /// <param name="ownerid">负责人</param>
        /// <returns></returns>
        public PageResult<AppointmentView> QryAppointmentList(Guid new_districtandcounty, int? statecode, Guid ownerid, int pageNum, int pageSize) {
            return QryAppointmentList(new_districtandcounty, statecode, null, null, ownerid, Guid.Empty, pageNum, pageSize);
        }

        /// <summary>
        /// 根据区域id，状态，时间，负责人查询拜访视图
        /// </summary>
        /// <param name="new_districtandcounty">区域id</param>
        /// <param name="statecode">状态</param>
        /// <param name="startDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <param name="ownerid">负责人</param>
        /// <returns></returns>
        public PageResult<AppointmentView> QryAppointmentList(Guid new_districtandcounty, int? statecode, string startDate
                                , string endDate, Guid ownerid, int pageNum, int pageSize)
        {
            return QryAppointmentList(new_districtandcounty, statecode, startDate, endDate, ownerid, Guid.Empty, pageNum, pageSize);
        }

        /// <summary>
        /// 根据区域id，状态，时间，负责人，拜访对象查询拜访视图
        /// </summary>
        /// <param name="new_districtandcounty">区域id</param>
        /// <param name="statecode">状态</param>
        /// <param name="startDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <param name="ownerid">负责人</param>
        /// <param name="contactId">拜访对象</param>
        /// <returns></returns>
        public PageResult<AppointmentView> QryAppointmentList(Guid new_districtandcounty, int? statecode, string startDate
                                , string endDate, Guid ownerid, Guid contactId,int pageNum, int pageSize)
        {
            IEnumerable<AppointmentView> appointmentList = appointmentDal.QryAppointmentListSecond(new_districtandcounty, statecode, startDate
                                    , endDate, ownerid, contactId, pageNum, pageSize+1).ToList(); ;

            PageResult<AppointmentView> pageResult = new PageResult<AppointmentView>();
            pageResult.existsnextdata = appointmentList.Count() > pageSize;
            pageResult.total = appointmentDal.QueryApppointmentCount(new_districtandcounty, statecode, startDate
                                    , endDate, ownerid, contactId);
            pageResult.datas = appointmentList.Skip(0).Take(pageSize).ToList();
            return pageResult;
        }

        /// <summary>
        /// 根据区域id，状态，时间，负责人，拜访对象查询拜访视图
        /// </summary>
        /// <param name="new_districtandcounty">区域id</param>
        /// <param name="statecode">状态</param>
        /// <param name="startDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <param name="ownerid">负责人</param>
        /// <param name="contactId">拜访对象</param>
        /// <returns></returns>
        public PageResult<AppointmentView> QryAppointmentListV2(Guid new_districtandcounty, int? statecode, string startDate
                                , string endDate, Guid ownerid, Guid contactId, int pageNum, int pageSize)
        {
            IEnumerable<AppointmentView> appointmentList = appointmentDal.QryAppointmentListSecondV2(new_districtandcounty, statecode, startDate
                                    , endDate, ownerid, contactId, pageNum, pageSize + 1).ToList(); ;

            PageResult<AppointmentView> pageResult = new PageResult<AppointmentView>();
            pageResult.existsnextdata = appointmentList.Count() > pageSize;
            pageResult.total = appointmentDal.QueryApppointmentCountV2(new_districtandcounty, statecode, startDate
                                    , endDate, ownerid, contactId);
            pageResult.datas = appointmentList.Skip(0).Take(pageSize).ToList();
            return pageResult;
        }

        /// <summary>
        /// 查询拜访
        /// </summary>
        /// <param name="activityId">拜访id</param>
        /// <returns></returns>
        public AppointmentView QryAppointment(Guid activityId) {
              return appointmentDal.QryAppointment(activityId);
        }
    }
}
